package com.xm.linxiaogang.network.retrofit

import com.example.baselibrary.BuildConfig
import com.xm.linxiaogang.network.bean.FastJsonConverterFactory
import com.xm.linxiaogang.network.body.UploadRequestBody
import com.xm.linxiaogang.network.interceptor.ReceivedInterceptor
import com.xm.linxiaogang.network.interceptor.RequestInterceptor
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import java.io.File
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLSession
import javax.net.ssl.SSLSocketFactory

/**
 * 网络请求工具类
 */
object RetrofitUtil {
    //时延
    private const val TIME_OUT = 60 * 1000L

    /**
     * 获取API接口
     *
     * @param tClass API 类
     * @param host   API的域名（必须以 / 结尾）
     * @param sp     SharePreference 用于保存token、header等
     * @return
     */
    fun <T> getService(tClass: Class<T>, host: String): T {
        val builder = OkHttpClient.Builder()
            .addInterceptor(ReceivedInterceptor())
            .addInterceptor(RequestInterceptor())
            .connectTimeout(TIME_OUT, TimeUnit.MILLISECONDS)
            .readTimeout(TIME_OUT, TimeUnit.MILLISECONDS)
            .writeTimeout(TIME_OUT, TimeUnit.MILLISECONDS)
            .retryOnConnectionFailure(true)

        //日志输出
        if (BuildConfig.DEBUG) {
            builder.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.NONE))
        }

        //https证书认证
        val sslUtils: SSLUtils = SSLUtils.getIntance()
        val sslSocketFactory: SSLSocketFactory? = sslUtils.setCertificates()
        if (sslSocketFactory != null)
            builder.hostnameVerifier { hostname: String, session: SSLSession ->
                hostname == session.peerHost //主机名和url的校验
            }.sslSocketFactory(sslSocketFactory, SSLUtils.x509TrustManager) //设置证书管理器

        val okHttpClient = builder.build()
        val retrofit = Retrofit.Builder()
            .baseUrl(host)
            .client(okHttpClient)
            .addConverterFactory(FastJsonConverterFactory.create()) //添加 fastJson 解析器
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) //添加 RxJava 适配器
            .build()
        return retrofit.create(tClass)
    }

    /**
     * 上传文件时对请求头进行包装
     *
     * @param key  文件对应的key
     * @param path 文件路径
     * @return
     */
    fun getRequestPart(
        key: String,
        path: String,
        callback: UploadRequestBody.UploadCallback
    ): MultipartBody.Part {
        val file = File(path)
        val body = UploadRequestBody(file, callback)
        // RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        return MultipartBody.Part.createFormData(key, file.name, body)
    }

}